package com.cz.basetool.ui_work.util.system.resource;

import android.content.res.Resources;

import java.lang.reflect.Field;

/**
 * Created by XinYi on 2019/4/1.
 * 获取系统资源com.android.internal.R
 *
 */

public class SystemResourceManager {

    /**
     * 适用于找 com.android.internal.R.id.xx
     * @param id
     * @return
     */
    public static int getResourceId(String id){
        return getResourceId("id",id);
    }

    /**
     * 适用于找 com.android.internal.R.layout.xx
     * @param id
     * @return
     */
    public static int getResourceLayoutId(String id){
        return getResourceId("layout",id);
    }

    /**
     * 适用于找 com.android.internal.R.styleable.xx
     * @param id
     * @return
     */
    public static int getResourceStyleableId(String id){
        return getResourceId("styleable",id);
    }

    /**
     * 适用于找 com.android.internal.R.styleable.xx
     * @param id
     * @return      数组
     */
    public static int[] getResourceStyleableIds(String id){
        return getResourceIds("styleable",id);
    }

    /**
     * 适用于找 com.android.internal.R.attr.xx
     * @param id
     * @return
     */
    public static int getResourceAttrId(String id){
        return getResourceId("attr",id);
    }


    /**
     * 通用找id方法
     * @param resourceType
     * @param id
     * @return
     */
    public static int getResourceId(String resourceType,String id){
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$" + resourceType);
            Field field = clazz.getDeclaredField(id);
            field.setAccessible(true);
            return (int) field.get(null);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return -1;
    }


    /**
     * 通用找id方法
     * @param resourceType
     * @param id
     * @return
     */
    public static int[] getResourceIds(String resourceType,String id){
        try {
            Class<?> clazz = Class.forName("com.android.internal.R$" + resourceType);
            Field field = clazz.getDeclaredField(id);
            field.setAccessible(true);
            return (int[]) field.get(null);         //注意用get方法，不能用getInt方法，否则报错：Not a primitive field
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}
